// pages/scanresult/scanresult.js
var util = require("../../utils/util.js");
var IntervalGetBoxState;
var IntervalgetBoxLockState;
var opentime;
var closetime;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _order_bn: "",
    _order_id: "",
    isCreateOrder: 0,
    isLocked:1,
    doClose:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options + "分享带参数");
    console.log(options);
    this.setData({
      _box_bn: options.box_bn,
      _box_id: options.box_id
    })
    wx.setNavigationBarTitle({
      title: '共享智能箱',
    })
    var that = this;
    var _box_bn = options.box_bn;

    // that.getBoxLockState(_box_bn);
    IntervalgetBoxLockState = setInterval((function callback() {
      that.getBoxLockState(_box_bn);
      var isLocked = that.data.isLocked;
      console.log(isLocked)
      console.log(isLocked + '进入页面-箱子开关状态')
      if (isLocked == 0) { // 已经打开，结束轮询
        clearInterval(IntervalgetBoxLockState);//取消轮询  
        //显示 打开后界面（请合上箱盖）
        wx.setNavigationBarTitle({
          title: '开箱成功',
        })
        wx.showToast({
          title: '开箱成功',
          icon: "success"
        })
        that.setData({
          isLocked: 0,
          doClose: 0
        })
      }
    }).bind(this), 3000);
  
    opentime = setTimeout(function () {
      clearInterval(IntervalgetBoxLockState);//取消轮询  
      var isLocked = that.data.isLocked;
      if (isLocked == 1) {
        wx.showModal({
          title: '提示',
          content: '开箱失败，请重新扫码开箱',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            }
          },
          showCancel: false
        })
      }
    }, 80000)
  },



  // 判断箱子是锁住  
  getBoxLockState: function (_box_bn) {
    var that = this;
    wx.request({
      url: "https://boxapi.supergk.com/server/box/query_box_lock_status",
      header: {
        'content-type': 'application/json'
      },
      method: "GET",
      data: {
        box_bn: _box_bn
      },
      success: function (result) {
        console.log(result)
        if (result.data.code == 0) {
          console.log("操作成功");
          console.log(result.data.msg);
          if (result.data.data.lock1_state == "close") {
            console.log("箱子锁住")
            that.setData({
              isLocked: 1,
            });
          } else if (result.data.data.lock1_state == "open") {
            console.log("箱子未锁住")
            that.setData({
              isLocked: 0,
            });
          }
          // //成功提示
          // wx.showToast({
          //   title: result.data.msg,
          //   icon: "success"
          // })
        } else {
          console.log(result.data.msg)
          wx.showModal({
            title: '提示',
            content: result.data.msg,
            showCancel: false
          })
        }
      }
    })
  },

  // 点击已经合上箱盖
  tapClosedBox: function () {
    var that = this;
    var _box_bn = that.data._box_bn;
    var isLocked = that.data.isLocked;
    clearTimeout(opentime);
    that.setData({
      doClose:1,
    })
    wx.showToast({
      title: '关箱中',
      icon: "success"
    })
    // that.getBoxLockState(_box_bn);
    IntervalgetBoxLockState = setInterval((function callback() {
      that.getBoxLockState(_box_bn);
      var isLocked = that.data.isLocked;
      
      if (isLocked == 1) { // 已经锁上，结束轮询
        clearInterval(IntervalgetBoxLockState);//取消轮询  
        clearTimeout(closetime);
        //显示 关闭后界面（设置收件人）
        that.setData({
          isLocked: 1,//实际为1，等创建订单成功后再设为1
        })

        // 创建订单
        var user_id = wx.getStorageSync("userInfo").userInfo.uid;
        console.log(user_id);

        const requestgetBoxState = wx.request({
          url: "https://boxapi.supergk.com/server/order/create",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          data: util.json2Form({
            user_id: user_id,
            box_id: that.data._box_id
          }),
          success: function (result) {
            console.log(result)
            if (result.data.code == 0) {
              console.log("订单创建成功");
              console.log(result)
              that.setData({
                isLockedHide: 1,//创建订单成功
                _order_id: result.data.data.order_id,
                _order_bn: result.data.data.order_bn,
                isCreateOrder: 1,
                doClose: 1,
                isLocked:1,
              });
              wx.setNavigationBarTitle({
                title: '订单创建成功',
              })
              wx.showToast({
                title: '关箱成功',
                icon: "success"
              })
              // //创建订单成功提示
              // wx.showToast({
              //   title: result.data.msg,
              //   icon: "success"
              // })

              // 开箱成功后  请求 进行中订单接口 刷新进行中订单数
              //获取正在进行中的订单个数
              var _uid = wx.getStorageSync("userInfo").userInfo.uid;
              const requestorderingNum = wx.request({
                url: 'https://boxapi.supergk.com/server/order/query_going_order_count',
                data: {
                  uid: _uid
                },
                header: {
                  'content-type': 'application/json'
                },
                method: "GET",
                success: function (res) {
                  if (res.data.code == "0") {
                    that.setData({
                      orderingNum: res.data.data.count,
                    })
                  } else {
                    console.log();
                  }
                }
              })//获取正在进行中的订单个数 結束

              // 存储当前订单信息
              wx.setStorage({
                key: 'orderInfoNow',
                data: {
                  orderInfoNow: result.data.data,
                },
                success: function (res) {
                  console.log("存储成功")
                },
              })
            } else {
              console.log(result.data.msg)
              wx.showModal({
                title: '提示',
                content: result.data.msg,
                showCancel: false
              })
            }
          }
        })
      }

    }).bind(this), 3000);

   closetime = setTimeout(function () {
      clearInterval(IntervalgetBoxLockState);//取消轮询  
      var isLocked = that.data.isLocked;
      if (isLocked == 0){
        wx.showModal({
          title: '提示',
          content: '请确认箱盖是否已关闭',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                doClose: 0,
              })
            }
          },
          showCancel:false
        })
      }
    }, 80000)
  },
//  test
// tapClosetest:function(){
//   var that = this;
//   var countdown = 5;
//   var interval;
//   if (countdown > 0) {
//     interval = setInterval(function () {
//       that.setData({
//         button_reqIdentifyCode: '重新获取(' + countdown + 's)'
//       });
//       countdown--;
//       if (countdown <= 0) {
//         countdown = -1
//         that.setData({
//           button_reqIdentifyCode: '获取验证码'
//         });
//         clearInterval(interval)
//       }
//     }, 1000)
//   }
// },

  // 点击报障页面
  moveToWarn: function () {
    var box_id = this.data._box_id;
    var box_bn = this.data._box_bn
    wx.redirectTo({
      url: '../informant/informant?box_id=' + box_id + '&box_bn=' + box_bn
    })
  },

  // 点击选择我的收件人
  // moveToMyRecipients: function () {
  //   var order_id = this.data._order_id;
  //   var order_bn = this.data._order_bn
  //   wx.redirectTo({
  //     url: '../my/myrecipients-sendbox/myrecipients-sendbox?order_id=' + order_id + '&order_bn=' + order_bn
  //   })
  // },

  moveToMyRecipients: function (e) {
    const dataset = e.currentTarget.dataset;
    var order_id = dataset.orderid;
    var order_bn = dataset.orderbn;
    wx.navigateTo({
      url: '../my/myrecipients-sendbox/myrecipients-sendbox?order_id=' + order_id + '&order_bn=' + order_bn
    })
  },

  // 点击邀请我的好友
  shareToWechat: function () {
    var order_id = this.data._order_id;
    wx.showModal({
      title: '分享给好友',
      content: '点击右上角分享给好友即可',
    })

  },
  moveToIndex: function () {
    wx.redirectTo({
      url: '../index/index'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  //分享
  onShareAppMessage: function () {
    var order_id = this.data._order_id;
    // var path = '/pages/scanresult/scanresult?isShare=1&order_id=' + order_id;
    var path = '/pages/my/ordeDetail/ordeDetail?isShare=1&order_id=' + order_id;
    return {
      title: "我发送了一个智能箱子给你",
      path: path
    }
  }

})